<template>
  <div style="border: 1px solid #ccc">
    <Toolbar
      style="border-bottom: 1px solid #ccc;"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :mode="mode"
    />
    <Editor
      style="height: 400px; overflow-y: hidden;"
      v-model="valueHtml"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onChange="handleChange"
      @onCreated="handleCreated"
    />
  </div>
</template>
<script>
import '@wangeditor/editor/dist/css/style.css' // 引入 css

import { onBeforeUnmount, shallowRef, inject ,reactive, ref, onMounted  } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { DomEditor, getAllMenuKeys, IToolbarConfig, createToolbar   } from '@wangeditor/editor'

export default {
  components: { Editor, Toolbar },
  props:{
    sendData:{
      Type:String,
      default:""
    },
    valueHtml:{
      type:String,
      default:""
    }
  },
  setup(props,{emit}) {

    const $api = inject("$api");

    // 编辑器实例，必须用 shallowRef
    const editorRef = shallowRef();
    // console.log(props,'props')

    // 内容 HTML
    const valueHtml = ref('')

    const toolbarConfig = reactive({
      excludeKeys :['group-video','insertImage']
    })
    const editorConfig = { placeholder: '请输入内容...', MENU_CONF: {} }

    editorConfig.MENU_CONF['uploadImage'] = {
        // 自定义插入图片
        async customUpload (res, insertFn) { 
          console.log(res,insertFn,'insertFn')                 // JS 语法
            // res 即服务端的返回结果
            let imgFile = res;
            // console.log(resultFiles);
            let pic = new FormData();
            pic.append('files',imgFile);

            $api.uploadList(pic).then(res=>{
                console.log(res,'uploadMultipartFile');
                if(res){
                    insertFn(res.path)
                    // this.loading = false;
                }
            })
            // 从 res 中找到 url alt href ，然后插图图片
            // insertFn(url, alt, href)
        },
    }

    onMounted(()=>{
      setTimeout(() => {
        if(props.valueHtml){
          valueHtml.value = props.valueHtml
        }
      }, 500)
    })

    // 组件销毁时，也及时销毁编辑器
    onBeforeUnmount(() => {
        const editor = editorRef.value
        if (editor == null) return
        editor.destroy()
    })

    const handleChange = (editor) => { 
      // console.log('change:', valueHtml.value) 
      // console.log('valueHtml.value:', valueHtml.value) 
      let value = valueHtml.value;
      emit('handleChange', {value})
    }

    const handleCreated = (editor) => {
      
      editorRef.value =  editor // 记录 editor 实例，重要！
    }

    return {
      editorRef,
      valueHtml,
      mode: 'default', // 或 'simple'
      toolbarConfig,
      editorConfig,
      handleCreated,
      handleChange,
    };
  }
}
</script>    